package com.booksystem.campuslibrarymanagementsystem.controller.approve;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.booksystem.campuslibrarymanagementsystem.commen.request.approverequest.Onlinemanagement.BorrowingApproval;
import com.booksystem.campuslibrarymanagementsystem.commen.request.approverequest.Onlinemanagement.RenewalApproval;
import com.booksystem.campuslibrarymanagementsystem.commen.request.approverequest.Onlinemanagement.ReservationApproval;
import com.booksystem.campuslibrarymanagementsystem.commen.request.approverequest.Onlinemanagement.ReturnApproval;
import com.booksystem.campuslibrarymanagementsystem.commen.result.Result;
import com.booksystem.campuslibrarymanagementsystem.entity.*;
import com.booksystem.campuslibrarymanagementsystem.service.*;
import com.booksystem.campuslibrarymanagementsystem.utils.JwtUtil;
import com.booksystem.campuslibrarymanagementsystem.utils.TimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@RequestMapping("/approval")
@Api(tags = "线上管理")
@RestController
public class OnlineManagementController {


    SystemTable systemTable = new SystemTable();
    BorrowApprovalsTable borrowApprovalsTable = new BorrowApprovalsTable();

    @Autowired
    private BorrowApprovalsTableService borrowApprovalsTableService;
    @Autowired
    private BorrowingRulesTableService borrowingRulesTableService;
    @Autowired
    private ReturnrequesTableService returnrequesTableService;
    @Autowired
    private ReservationTableService reservationTableService;
    @Autowired
    private RenewalapprovalTableService renewalapprovalTableService;

    @PostMapping("/BorrowingApproval")
    @ApiOperation(value = "借阅审批", notes = "借阅审批")
    public Result Borrowingapproval(@RequestBody BorrowingApproval borrowingApproval) {
        Map<String, Object> parsed = JwtUtil.tokenPre(borrowingApproval.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            if (identity.equals("approval")) {
                String account = borrowingApproval.getAccount();//借阅者账户id
                String approvalTime = TimeUtil.getTime();//自动生成审批时间
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate expirationDate = LocalDate.parse(approvalTime, formatter);
                String bookid = borrowingApproval.getBookid();//图书id
                String approvalResult = borrowingApproval.getApprovalResult();
                // 检查该用户借阅审批记录
                List<BorrowApprovalsTable> borrowingApprovalList = borrowApprovalsTableService.queryByAccount(account);
                if (borrowingApprovalList == null) {
                    // 如果没有审批记录，可以根据业务需求决定是否允许审批或返回错误信息
                    return Result.fail(String.format("该账户(%s)没有借阅审批记录", account));
                }
                // 4. 更新审批结果
                boolean foundAndUpdated = false;
                for (BorrowApprovalsTable entry : borrowingApprovalList) {
                    if (entry.getAccount().equals(account) && String.valueOf(entry.getBookid()).equals(String.valueOf(bookid))) {
                        entry.setApprovalstate(approvalResult);
                        entry.setApprovaldate(TimeUtil.getTime()); // 设置审批时间
                        // 使用 Wrapper 更新记录
                        QueryWrapper<BorrowApprovalsTable> updateWrapper = new QueryWrapper<>();
                        updateWrapper.eq("account", account)
                                .eq("bookid", bookid);
                        borrowApprovalsTableService.update(entry, updateWrapper); // 更新审批记录
                        foundAndUpdated = true;
                        // 5. 返回相应结果
                        if ("通过".equals(approvalResult)) {
                            borrowApprovalsTableService.onapproval(account, expirationDate, bookid, approvalResult);
                            return Result.success(entry, 1); // 返回审批成功的结果
                        } else if ("未通过".equals(approvalResult)) {
                            borrowApprovalsTableService.unapproval(account, expirationDate, bookid, approvalResult);
                            // 直接返回未通过的结果
                            return Result.fail("未通过");
                        }
                    }
                }
                // 调用Service层的approve方法
            } else {
                return Result.fail("身份权限不足");
            }
        } else{
            return Result.fail("请输入正确token值");
        }
        return Result.success("审批完成",1);
    }
    @PostMapping("/ReturnApproval")
    @ApiOperation(value = "归还审批", notes = "归还审批")
    public Result ReturnApproval(@RequestBody ReturnApproval returnApproval) {
        Map<String, Object> parsed = JwtUtil.tokenPre(returnApproval.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            if (identity.equals("approval")) {
                String account = returnApproval.getAccount();//借阅者账户id
                String approvalTime = TimeUtil.getTime();//自动生成审批时间
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate expirationDate = LocalDate.parse(approvalTime, formatter);
                String bookid = returnApproval.getBookid();//图书id
                String approvalResult = returnApproval.getApprovalResult();
                // 检查该用户借阅审批记录
                List<ReturnrequesTable> returnrequesTableslist = returnrequesTableService.queryByAccount(account);
                if (returnrequesTableslist == null) {
                    // 如果没有审批记录，可以根据业务需求决定是否允许审批或返回错误信息
                    return Result.fail(String.format("该账户(%s)没有借阅审批记录", account));
                }
                // 4. 更新审批结果
                boolean foundAndUpdated = false;
                for (ReturnrequesTable entry : returnrequesTableslist) {
                    if (entry.getAccount().equals(account) && String.valueOf(entry.getBookid()).equals(String.valueOf(bookid))) {
                        entry.setApprovalstate(approvalResult);
                        entry.setApprovaldate(TimeUtil.getTime()); // 设置审批时间
                        // 使用 Wrapper 更新记录
                        QueryWrapper<ReturnrequesTable> updateWrapper = new QueryWrapper<>();
                        updateWrapper.eq("account", account)
                                .eq("book_id", bookid);
                        returnrequesTableService.update(entry, updateWrapper); // 更新审批记录
                        foundAndUpdated = true;
                        // 5. 返回相应结果
                        if ("通过".equals(approvalResult)) {
                            returnrequesTableService.onapproval(account, expirationDate, bookid, approvalResult);
                            return Result.success(entry, 1); // 返回审批成功的结果
                        } else if ("未通过".equals(approvalResult)) {
                            returnrequesTableService.unapproval(account, expirationDate, bookid, approvalResult);
                            // 直接返回未通过的结果
                            return Result.fail("未通过");
                        }
                    }
                }

            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
        return Result.success("审批完成",1);
    }

    @PostMapping("/RenewalApproval")
    @ApiOperation(value = "续借审批", notes = "续借审批")
    public Result RenewalApproval(@RequestBody RenewalApproval renewalApproval) {
        Map<String, Object> parsed = JwtUtil.tokenPre(renewalApproval.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            if (identity.equals("approval")) {
                String account = renewalApproval.getAccount();//借阅者账户id
                String approvalTime = TimeUtil.getTime();//自动生成审批时间
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate expirationDate = LocalDate.parse(approvalTime, formatter);
                String bookid = renewalApproval.getBookid();//图书id
                String approvalResult = renewalApproval.getApprovalResult();
                // 检查该用户借阅审批记录
                List<RenewalapprovalTable> renewalapprovalTableList = renewalapprovalTableService.queryByAccount(account);
                if (renewalapprovalTableList == null) {
                    // 如果没有审批记录，可以根据业务需求决定是否允许审批或返回错误信息
                    return Result.fail(String.format("该账户(%s)没有借阅审批记录", account));
                }
                // 4. 更新审批结果
                boolean foundAndUpdated = false;
                for (RenewalapprovalTable entry : renewalapprovalTableList) {
                    if (entry.getAccount().equals(account) && String.valueOf(entry.getBookid()).equals(String.valueOf(bookid))) {
                        entry.setApprovalstate(approvalResult);
                        entry.setApprovaldate(TimeUtil.getTime()); // 设置审批时间
                        // 使用 Wrapper 更新记录
                        QueryWrapper<RenewalapprovalTable> updateWrapper = new QueryWrapper<>();
                        updateWrapper.eq("account", account)
                                .eq("book_id", bookid);
                        renewalapprovalTableService.update(entry, updateWrapper); // 更新审批记录

                        foundAndUpdated = true;

                        // 5. 返回相应结果
                        if ("通过".equals(approvalResult)) {
                            returnrequesTableService.onapproval(account, expirationDate, bookid, approvalResult);
                            return Result.success(entry, 1); // 返回审批成功的结果
                        } else if ("未通过".equals(approvalResult)) {
                            returnrequesTableService.unapproval(account, expirationDate, bookid, approvalResult);
                            // 直接返回未通过的结果
                            return Result.fail("未通过");
                        }
                    }
                }

            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
        return Result.success("审批完成",1);
    }

    @PostMapping("/ReservationApproval")
    @ApiOperation(value = "预约审批", notes = "预约审批")
    public Result ReservationApproval(@RequestBody ReservationApproval reservationApproval) {
        Map<String, Object> parsed = JwtUtil.tokenPre(reservationApproval.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            if (identity.equals("approval")) {
                String account = reservationApproval.getAccount();//借阅者账户id
                String approvalTime = TimeUtil.getTime();//自动生成审批时间
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate expirationDate = LocalDate.parse(approvalTime, formatter);
                String bookid = reservationApproval.getBookid();//图书id
                String approvalResult = reservationApproval.getApprovalResult();
                // 检查该用户借阅审批记录
                List<ReservationTable> reservationTableList = reservationTableService.queryByAccount(account);
                if (reservationTableList == null) {
                    // 如果没有审批记录，可以根据业务需求决定是否允许审批或返回错误信息
                    return Result.fail(String.format("该账户(%s)没有借阅审批记录", account));
                }
                // 4. 更新审批结果
                boolean foundAndUpdated = false;
                for (ReservationTable entry : reservationTableList) {
                    if (entry.getAccount().equals(account) && String.valueOf(entry.getBookid()).equals(String.valueOf(bookid))) {
                        entry.setStatus(approvalResult);
                        entry.setApprovaldate(TimeUtil.getTime()); // 设置审批时间
                        // 使用 Wrapper 更新记录
                        QueryWrapper<ReservationTable> updateWrapper = new QueryWrapper<>();
                        updateWrapper.eq("account", account)
                                .eq("book_id", bookid);
                        reservationTableService.update(entry, updateWrapper); // 更新审批记录

                        foundAndUpdated = true;

                        // 5. 返回相应结果
                        if ("通过".equals(approvalResult)) {
                            returnrequesTableService.onapproval(account, expirationDate, bookid, approvalResult);
                            return Result.success(entry, 1); // 返回审批成功的结果
                        } else if ("未通过".equals(approvalResult)) {
                            returnrequesTableService.unapproval(account, expirationDate, bookid, approvalResult);
                            // 直接返回未通过的结果
                            return Result.fail("未通过");
                        }
                    }
                }

            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
        return Result.success("审批完成",1);
    }


    @PostMapping("/borrowingApprovalLists")
    @ApiOperation(value = "借阅审批列表", notes = "借阅审批总列表")
    public Result<List<BorrowApprovalsTable>> borrowingApprovalLists() {
        List<BorrowApprovalsTable> approvalLists = borrowApprovalsTableService.list();
        return Result.success(approvalLists,"查询成功",1);
    }
    /**
     * 根据approvalstate来查询
     */
    @GetMapping("/borrowingApprovalLists/{approvalstate}")
    @ApiOperation(value = "根据审批状态查询借阅审批列表", notes = "根据审批状态返回所有借阅审批信息")
    public Result<List<BorrowApprovalsTable>> getBorrowingApprovalByApprovalState(@PathVariable String approvalstate) {

        if (approvalstate.equals("1")){
            approvalstate = "通过";
        }else if (approvalstate.equals("0")){
            approvalstate = "未通过";
        }
        List<BorrowApprovalsTable> approvals = borrowApprovalsTableService.getByApprovalState(approvalstate);
        return Result.success(approvals, approvals.size());
    }
}



